package com.i2works.smartluolong.web.utils;

import com.alibaba.fastjson.JSONException;


import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;


import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Date;

/**
 * Created by DtDream on 2017/2/13.
 */


public class HttpUtils {
	
	private final static String appId ="0000xjy1";
	
	private final static String appSecret ="23a50ce2-bb07-400c-a469-6d6f9f4c84d";
	
    /*请求url获取返回的内容*/
    public static String getReturn (String url, String headerParams) {
    	
    	    
        try {
            HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
            SSLContext sc = null;
            sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            StringBuffer buffer = new StringBuffer();
            URL serverUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) serverUrl.openConnection();
            conn.setRequestMethod("GET");
            //必须设置false，否则会自动redirect到重定向后的地址
            conn.setInstanceFollowRedirects(false);
            conn.setRequestProperty("Authorization", headerParams);
            conn.connect();
            //将返回的输入流转换成字符串
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            String result = buffer.toString();
            return result;
        } catch (Exception e) {
            return null;
        }
    }

    public static String executePost(String url, String json) {
        String result = "fail";
		// 第一步，创建HttpPost对象
        DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);
		// 第二步，设置HTTP POST请求参数，  使用json对象
		try {
			StringEntity entity = new StringEntity(json,"utf-8"); 		// 解决中文乱码问题
			entity.setContentEncoding("UTF-8");    
			entity.setContentType("application/json");
			httpPost.setEntity(entity);
			    
			// 发起请求
			HttpResponse httpResponse = httpClient.execute(httpPost);  	
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {   
            	// 请求结束，返回结果。并解析json。  
            	result = EntityUtils.toString(httpResponse.getEntity());
            }   
	    	// 省略了一堆的catch（上面不少函数需捕捉异常）
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
		//httpClient.getConnectionManager().shutdown();
		}
        
        
        return result;
    }

    /**
     * 发送带签名的GET请求
     * @param url
     * @param queryString
     * @return
     */
    public static String sendGet(String url, String queryString) {
        url += "?" + queryString;// url是路径，queryString是参数
        String timeStamp = Long.toString(new Date().getTime());
        String key = appId;
        String secret = appSecret;
        String strToSign = SecurityUtils.getSignString(queryString, "GET", timeStamp);
        String signatureCalc = SecurityUtils.signWithHmac(strToSign, secret);
        String authorization = "appId=" + key + ",time=" + timeStamp + ",sign=" + signatureCalc;
        String result = HttpUtils.getReturn(url, authorization);
        System.out.println(result);
        return result;
    }

    
	public static String doGet(String httpurl) {
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;// 返回结果字符串
        try {
            // 创建远程url连接对象
            URL url = new URL(httpurl);
            // 通过远程url连接对象打开一个连接，强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式：get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取远程返回的数据时间：60000毫秒
            connection.setReadTimeout(60000);
            // 发送请求
            connection.connect();
            System.out.println(connection.getResponseCode());
            // 通过connection连接，获取输入流
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                // 封装输入流is，并指定字符集
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                // 存放数据
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            connection.disconnect();// 关闭远程连接
        }
        return result;
    }

    /**
     * 发送请求
     * @param url
     *            访问路径
     * @param submitMethod
     *            提交方法
     * @param queryString
     *            参数
     * @param dataFormat
     *            数据格式
     * @return
     * @throws IOException
     */
    public static String connections(String url, String submitMethod, String queryString, String dataFormat) {
        try {
            HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
            SSLContext sc = null;
            sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            StringBuffer result = new StringBuffer(); // 用来接受返回值
            URL uri = new URL(url);
            HttpURLConnection urlConnection = (HttpURLConnection) uri.openConnection();// 创建的http连接
            urlConnection.setRequestProperty("content-type", dataFormat);
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setRequestMethod(submitMethod);
            PrintWriter printWriter = new PrintWriter(urlConnection.getOutputStream());
            printWriter.print(queryString);
            printWriter.flush();
            urlConnection.connect();
            InputStream in = urlConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));// 接受连接受的参数
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line);
            }
            bufferedReader.close();
            return result.toString();
        } catch (Exception e) {
            return e.toString();
        }
    }



    static TrustManager[] trustAllCerts = new TrustManager[] { 
    		new X509TrustManager() {
		        @Override
		        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		            // TODO Auto-generated method stub
		        }
		
		        @Override
		        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		            // TODO Auto-generated method stub
		        }
		
		        @Override
		        public X509Certificate[] getAcceptedIssuers() {
		            // TODO Auto-generated method stub
		            return null;
		        }
        } 
   };   

}
